function checkPermission() {
    var r = getCookie('is_allowed');
    if(parseInt(r) != 1) {
        window.location.href = '/?from=' + encodeURIComponent(window.location.href);
    }
}
function getQueryStr(uri, name){
    var rs = new RegExp("(^|)"+name+"=([^\&]*)(\&|$)","gi").exec(uri), tmp;

    if(tmp=rs){
        return tmp[2];
    }

    // parameter cannot be found
    return "";
}
function dealFromLink() {
    document.getElementById('from').value = getQueryStr(window.location.href, 'from');
}
//自动修改字号
function autoFontSize() {
    var size = screen.width / 64;
    document.body.style.fontSize = size + 'px';
    document.body.setAttribute('data-font_size', size);
}
//修改字号
function changeFontSize(size) {
    document.body.style.fontSize = size + 'px';
    document.body.setAttribute('data-font_size', size);
    showContent();
}
//获得字号
function getFontSize() {
    var size = document.body.getAttribute('data-font_size');
    return parseInt(size);
}
//增大字号
function increaseFontSize() {
    var size = getFontSize();
    changeFontSize(parseInt(size) + 1);
}
//减小字号
function decreaseFontSize() {
    var size = getFontSize();
    changeFontSize(parseInt(size) - 1);
}
//自动开灯关灯
function autoLight() {
    var light = getCookie('light');
    if(light == 'light_off') {
        var tmp = document.getElementById('content').className;
        new_class_name = tmp.replace(/light_on/, 'light_off');
        document.getElementById('content').className = new_class_name;
    }
}
//开灯关灯
function changeLight() {
    var tmp = document.getElementById('content').className;
    var new_class_name = '';
    if(tmp.indexOf('light_on') != -1) {
        new_class_name = tmp.replace(/light_on/, 'light_off');
        setCookie('light', 'light_off', 29);
    }
    else {
        new_class_name = tmp.replace(/light_off/, 'light_on');
        setCookie('light', 'light_on', 29);
    }
    document.getElementById('content').className = new_class_name;
}
function createHttp(method, uri) {
    var xmlhttp=null;
    if (window.XMLHttpRequest) {//Firefox, Opera, IE7, etc.
        xmlhttp=new XMLHttpRequest();
    }
    else if (window.ActiveXObject) {//IE6, IE5
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
    if (xmlhttp!=null) {
        return xmlhttp;
    }
    else {
        return false;
    }
}
function getBookStartNum() {
    var start = 0;
    var uri = window.location.href;
    var tmp = uri.indexOf('#');
    if(tmp != -1) {
        start = parseInt(uri.substring(tmp+1));
    }
    return start;
}
var article_start = 0;
function getBookSid() {
    var uri = window.location.href;
    var dir = uri;
    var pos = uri.indexOf('#');
    if(pos != -1) {
        dir = uri.substring(0, pos);
    }
    pos = uri.lastIndexOf('/');
    return dir.substring(pos);
}
var book_sid = getBookSid();

function getArticle() {
    var book_start = arguments[0] ? parseInt(arguments[0]) : getBookStartNum();
    var length_sum = 0;
    var article_num = null;
    for(var i=0,l = articles.length; i<l; i++) {
        length_sum += parseInt(articles[i]['length']);
        if(length_sum > book_start) {
            article_num = parseInt(articles[i]['number']);
            if(i>0) { //i>0时，即第二篇、第三篇等等，假设每篇1000字，则2500是第三篇
                article_start = book_start - (length_sum - articles[i]['length']); //2500 - (3000 - 1000) = 500，即第三篇的第500字开始
            } else { //i=0 时，即第一篇
                article_start = book_start;
            }
            break;
        }
    }
    if(article_num == null) {
        return false;
    }
    var uri = window.location.href;
    var dir = uri;
    var pos = uri.indexOf('#');
    if(pos != -1) {
        dir = uri.substring(0, pos);
    }
    dir += '/';
    uri = dir + article_num + '.txt';
    var xmlhttp = createHttp();
    xmlhttp.open('GET', uri, false);
    xmlhttp.send();
    var r = xmlhttp.responseText;
    document.body.setAttribute('data-article', r);
    return true;
}
/**
 * 普通情况：在一篇中翻页
 * 特殊情况：第二篇结尾，需补满第三篇
 */
function showContent() {
    var tmp = document.body.getAttribute('data-article');
    var article = decodeURIComponent(window.atob(tmp));
    var size = getFontSize();
    var content_height = parseInt(document.documentElement.clientHeight) - size * 2; //高度 - padding
    //一屏最多几行，向下舍去。行高是1.2。减是为了保险不出现滚动条。todo 不减就会出。如果一屏就两段，还是会出滚动条，因为字太多。
    var one_page_max_line = Math.floor(content_height / (size * 1.2)) - 2;
    var one_line_max_words = (window.screen.availWidth - 12 * size) / size; //这个不能取整，因为乘以行数会多出来几个字。
    var one_page_max_words = one_page_max_line * one_line_max_words;
    var book_start = getBookStartNum();
    var left_article = article.substring(article_start);
    var new_article = '<p>';
    var this_page_words_count = 0;
    var article_end = false;
    var is_last_p = false;

    var used_line_count = 0;
    var cookie_article_end = getCookie('article_end');
    if(cookie_article_end == book_sid) { //说明是这本书的
        used_line_count = parseInt(getCookie('used_line_count'));
        setCookie('article_end', 0, -1000);
        setCookie('used_line_count', 0, -1000);
    }

    for(; used_line_count < one_page_max_line; used_line_count += new_p_line_count) {
        var new_p_words_count = left_article.indexOf("\n"); //换行的位置，即新一段有多少字
        if(new_p_words_count == -1) { //最后一段没有\n
            new_p_words_count = left_article.length;
            is_last_p = true;
        }
        new_p_line_count = Math.ceil((new_p_words_count + 2) / one_line_max_words) + 1; //新一段有多少行，向上舍入，+2是因为p缩进2个字，+1是因为每段下面都要加一行margin

        //如果 已用行数 + 新行数 > 一页最大行数，则需要截断
        //普通情况，没到最后一段，需要截断
        //特殊情况，到最后一段，需要截断
        if(used_line_count + new_p_line_count > one_page_max_line) {
            var cut_p_words_count = Math.floor((one_page_max_line - used_line_count) * one_line_max_words) - 2;
            cut_p_words_count = cut_p_words_count > new_p_words_count ? new_p_words_count : cut_p_words_count; //比如16 + 2 > 17，下面一行就一句话，理论截取太多了。
            var new_p = left_article.substring(0, cut_p_words_count);
            left_article = left_article.substring(cut_p_words_count + 1); //加1是为了跳过换行
            this_page_words_count += cut_p_words_count; //截断说明这一屏最后没有换行，不需要+1
        } else {
            if(is_last_p == true) {
                this_page_words_count += new_p_words_count; //最后一段没有\n
            } else {
                this_page_words_count += new_p_words_count + 1; //换行占1个字符
            }

            var new_p = left_article.substring(0, new_p_words_count);
            //普通情况，到本篇最后一段没截断
            if(is_last_p == true) {
                left_article = null; //最后一段，后面没有了
            } else {
                //普通情况，生成一屏的前几段
                left_article = left_article.substring(new_p_words_count + 1); //+1跳过换行
            }
        }

        //如果本屏第一段开头没有两个空格，那么是标题或者接上一页，不应该缩进。
        if((used_line_count == 0) && new_p.indexOf('  ') != 0) {
            new_article = '<p class="not_new">';
        }
        new_article = new_article + new_p + '</p><p>';
        
        //普通情况，到最后一段或者半段，没满一屏，需要取下一篇文章
        if((is_last_p == true) && (used_line_count + new_p_line_count < one_page_max_line)) {
            article_end = true;
            setCookie('used_line_count', used_line_count + new_p_line_count, 29);
            setCookie('length', this_page_words_count, 29);
            setCookie('article_end', book_sid, 29);
            break; //虽然本屏未满，但是要跳出。取下一篇补满。
        }
    }

    new_article += '</p>';
    new_article = new_article.replace(/<p><\/p>/g, ''); //删除空段
    new_article = new_article.replace(/  /g, ''); //删除两个空格
    var book_readed_words_count = book_start + this_page_words_count; //本书已读字数
    used_line_count += new_p_line_count;

    if(cookie_article_end == book_sid) {
        document.getElementById('content').innerHTML += new_article;
    } else {
        document.getElementById('content').innerHTML = new_article;
    }
    if(cookie_article_end == book_sid) { //这是set之前取的cookie，所以不受这次set影响
        var used_words = parseInt(getCookie('length'));
        book_readed_words_count += used_words;
    }
    document.getElementById('next_page').href = '#' + book_readed_words_count;
    //如果最后一段或者半段，没满一屏需要再取。
    if((article_end == true) && (used_line_count < one_page_max_line)) {
        var r = getArticle(book_readed_words_count);
        if(r == true) {
            showContent();
        } else { //如果取不到，说明是最后一篇了，本书结束。
            setCookie('length', 0, -1000);
            setCookie('article_end', 0, -1000);
            setCookie('used_line_count', 0, -1000);
            document.getElementById('next_page').href = location.hash;
        }
    } else { //如果满一屏，不需要再取。
        setCookie('length', 0, -1000);
        setCookie('article_end', 0, -1000);
        setCookie('used_line_count', 0, -1000);

    }

//document.getElementById('previous_page').href = '#' + start;
//todo 如何计算上一页的地址，是个难题
    return true;
}

function eventNextPage() {
    document.getElementById('next_page').onclick = function() {
        var tmp = this.href;
        window.location.href = tmp; //这样才能后退
        return false;
    }
}
function eventPreviousPage() {
    document.getElementById('previous_page').onclick = function() {
        if(location.hash != '') {
        history.go(-1); //todo 这是临时方案，当用户直接访问中间页时无法后退。
        }
        return false;
    }
}
function eventIncreaseFontSize() {
    document.getElementById('increase_font').onclick = function(){
        increaseFontSize();
        return false;
    }
}
function eventDecreaseFontSize() {
    document.getElementById('decrease_font').onclick = function(){
        decreaseFontSize();
        return false;
    }
}
function eventChangeLight() {
    document.getElementById('light_switch').onclick = function(){
        changeLight();
        return false;
    }
}
/**
 * hashchange.js
 * @author raphealguo(raphealguo@qq.com)
 * @date 2011/08/09
 */
var cur_hash = location.hash;//记录当前hash

function getHash(){//获取hash
    var h = location.hash;
    if (!h){
        return '';
    }else{
        return location.hash;
    }
}
function changeHashCallBack(){//hash变化之后，回调函数会被触发
    var hash = getHash();
    if (cur_hash != hash){
            cur_hash = hash;
            var r = getArticle();
            if(r == true) {
                showContent();
            }
    }
}

if (document.all && //辨别IE
    !document.documentMode//IE8才有documentMode
    ){
    /* 低于IE8的IE系列采用定时器监听 */
    setInterval(changeHashCallBack(), 100);
} else {
    window.onhashchange = changeHashCallBack;
}

function getCookie(c_name) {
    if (document.cookie.length>0) {
        c_start=document.cookie.indexOf(c_name + "=")
        if (c_start!=-1) { 
            c_start=c_start + c_name.length+1 
            c_end=document.cookie.indexOf(";",c_start)
            if (c_end==-1) c_end=document.cookie.length
            return unescape(document.cookie.substring(c_start,c_end))
        } 
    }
    return '';
}

function setCookie(c_name,value,expiredays) {
    var exdate=new Date()
    exdate.setDate(exdate.getDate()+expiredays)
    document.cookie=c_name+ "=" +escape(value)+
    ((expiredays==null) ? "" : ";expires="+exdate.toGMTString())
}
var base64 = {};
base64.PADCHAR = '=';
base64.ALPHA = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';

base64.makeDOMException = function() {
    // sadly in FF,Safari,Chrome you can't make a DOMException
    var e, tmp;

    try {
        return new DOMException(DOMException.INVALID_CHARACTER_ERR);
    } catch (tmp) {
        // not available, just passback a duck-typed equiv
        // https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Error
        // https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Error/prototype
        var ex = new Error("DOM Exception 5");

        // ex.number and ex.description is IE-specific.
        ex.code = ex.number = 5;
        ex.name = ex.description = "INVALID_CHARACTER_ERR";

        // Safari/Chrome output format
        ex.toString = function() { return 'Error: ' + ex.name + ': ' + ex.message; };
        return ex;
    }
}

base64.getbyte64 = function(s,i) {
    // This is oddly fast, except on Chrome/V8.
    //  Minimal or no improvement in performance by using a
    //   object with properties mapping chars to value (eg. 'A': 0)
    var idx = base64.ALPHA.indexOf(s.charAt(i));
    if (idx === -1) {
        throw base64.makeDOMException();
    }
    return idx;
}

base64.decode = function(s) {
    // convert to string
    s = '' + s;
    var getbyte64 = base64.getbyte64;
    var pads, i, b10;
    var imax = s.length
    if (imax === 0) {
        return s;
    }

    if (imax % 4 !== 0) {
        throw base64.makeDOMException();
    }

    pads = 0
    if (s.charAt(imax - 1) === base64.PADCHAR) {
        pads = 1;
        if (s.charAt(imax - 2) === base64.PADCHAR) {
            pads = 2;
        }
        // either way, we want to ignore this last block
        imax -= 4;
    }

    var x = [];
    for (i = 0; i < imax; i += 4) {
        b10 = (getbyte64(s,i) << 18) | (getbyte64(s,i+1) << 12) |
            (getbyte64(s,i+2) << 6) | getbyte64(s,i+3);
        x.push(String.fromCharCode(b10 >> 16, (b10 >> 8) & 0xff, b10 & 0xff));
    }

    switch (pads) {
    case 1:
        b10 = (getbyte64(s,i) << 18) | (getbyte64(s,i+1) << 12) | (getbyte64(s,i+2) << 6);
        x.push(String.fromCharCode(b10 >> 16, (b10 >> 8) & 0xff));
        break;
    case 2:
        b10 = (getbyte64(s,i) << 18) | (getbyte64(s,i+1) << 12);
        x.push(String.fromCharCode(b10 >> 16));
        break;
    }
    return x.join('');
}

base64.getbyte = function(s,i) {
    var x = s.charCodeAt(i);
    if (x > 255) {
        throw base64.makeDOMException();
    }
    return x;
}

base64.encode = function(s) {
    if (arguments.length !== 1) {
        throw new SyntaxError("Not enough arguments");
    }
    var padchar = base64.PADCHAR;
    var alpha   = base64.ALPHA;
    var getbyte = base64.getbyte;

    var i, b10;
    var x = [];

    // convert to string
    s = '' + s;

    var imax = s.length - s.length % 3;

    if (s.length === 0) {
        return s;
    }
    for (i = 0; i < imax; i += 3) {
        b10 = (getbyte(s,i) << 16) | (getbyte(s,i+1) << 8) | getbyte(s,i+2);
        x.push(alpha.charAt(b10 >> 18));
        x.push(alpha.charAt((b10 >> 12) & 0x3F));
        x.push(alpha.charAt((b10 >> 6) & 0x3f));
        x.push(alpha.charAt(b10 & 0x3f));
    }
    switch (s.length - imax) {
    case 1:
        b10 = getbyte(s,i) << 16;
        x.push(alpha.charAt(b10 >> 18) + alpha.charAt((b10 >> 12) & 0x3F) +
               padchar + padchar);
        break;
    case 2:
        b10 = (getbyte(s,i) << 16) | (getbyte(s,i+1) << 8);
        x.push(alpha.charAt(b10 >> 18) + alpha.charAt((b10 >> 12) & 0x3F) +
               alpha.charAt((b10 >> 6) & 0x3f) + padchar);
        break;
    }
    return x.join('');
}
if (!window.btoa) window.btoa = base64.encode
if (!window.atob) window.atob = base64.decode
/*window.onload = function() {
    eventIncreaseFontSize();
    eventDecreaseFontSize();
    autoLight();
    eventChangeLight();
    getArticle();
    showContent();
    eventNextPage();
    eventPreviousPage();
}*/
